! function() {
    var view = document.querySelector('.message')

    var model = {
        init: function() {
            let APP_ID = 'y8HJizhUQtiR9gn36Hk3xWfj-gzGzoHsz'
            let APP_KEY = 'dOcmcXo1Doyil203TdseUOmR'
            AV.init({ appId: APP_ID, appKey: APP_KEY })
        },
        //获取数据
        fetch: function() {
            var query = new AV.Query('message')
            return query.find() // Promise对象
        },
        //新建数据
        save: function(user, content) {
            var Message = AV.Object.extend('message')
            var message = new Message()
            return message.save({ // Promise对象
                name: user,
                words: content
            })
        }
    }

    var controller = {
        view: null,
        model: null,
        messageList: null,
        myForm: null,
        init: function(view, model) {
            this.view = view
            this.model = model
            this.messageList = view.querySelector('#messageList')
            this.myForm = view.querySelector('form')
            this.model.init()
            this.loadMessages()
            this.bindEvents()
        },
        bindEvents: function() {
            this.myForm.addEventListener('submit', (e) => {
                e.preventDefault()
                this.saveMessage()
            })
        },
        loadMessages: function() {
            this.model.fetch().then(
                (messages) => {
                    let array = messages.map(value => value.attributes)
                    array.forEach((value) => {
<<<<<<< HEAD
                        this.appendMessage(value.name, value.words)
=======
                        let li = document.createElement('li')
                        li.innerText = `${value.name} says: ${value.words}`
                        document.querySelector('#messageList').appendChild(li)
>>>>>>> 216d1d1a3396349fad54d823a642ec226b2d8eb9
                    })
                })
        },
        saveMessage: function() {
            let myForm = this.myForm
            let user = myForm.querySelector('input[name=user]').value
            let content = myForm.querySelector('input[name=content]').value
            let isUserEmpty = (user === '') || (user === null) || (user === undefined)
            let isContentEmpty = (content === '') || (content === null) || (content === undefined)
            let isOk = !(isUserEmpty || isContentEmpty)
            if (!isOk) {
                alert('用户名或评论不能为空!')
                return
            }
            this.model.save(user, content).then((object) => {
                this.appendMessage(user, content)
            })
        },
        appendMessage: function(user, content) {
            let li = document.createElement('li')
            li.innerText = `${user} says: ${content}`
            document.querySelector('#messageList').appendChild(li)
        }
    }

    controller.init(view, model)

}.call()